<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { accountFormSchema } from './account.data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';
  import { getDeptList } from '@/api/system/dept';
  import { isAccountExist,UpdateUser,AddAccount } from '@/api/system/platformuser'
  import { getCity } from '@/api/region/region'
  const { notification, createErrorModal } = useMessage();
  const { t } = useI18n();
  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      var update = ''
      const rowId = ref('');

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        update = data.record
        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          data.record['roleId'] = data.record['role']['id'];
          data.record['deptName'] = data.record['dept']['deptName'];
          setFieldsValue({
            ...data.record,
          });
        }
        const apidata = await getDeptList(null);
        const treeData = apidata.data
        updateSchema([
          {
            field: 'Password',
            required: !unref(isUpdate),
          },
          // {
          //   field: 'confirmPassword',
          //   show: !unref(isUpdate),
          // },
          {
            field: 'deptName',
            componentProps: { treeData },
          }
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        const values = await validate();
        try {
           setModalProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            // update
            if(values.account != update['account']){
              const is_has_account = await isAccountExist(values.account);
              if(is_has_account.code != 200){
                notification.error({
                message: t('sys.update.error'),
                description: is_has_account.message,
                duration: 3,
              });
              }
            }
            // 调用接口
            var update_data = {
              userId:update['userId'],
              password:(values.Password == undefined || values.Password == '') ? "" : values.Password,
              confirmPassword:(values.Password == undefined || values.Password == '') ? "" : values.confirmPassword,
              account:values.account,
              phoneNum:values.phoneNum,
              email:values.email,
              dept:values.deptName == update['deptName'] ? update['deptId']:values.deptName,
              role:values.roleId,
            }
            const update_menu = await UpdateUser(update_data)
             if(update_menu.code == 200){
                notification.success({
                message: t('sys.update.success'),
                description: t('sys.update.success'),
                duration: 3,
              });
                  setModalProps({ confirmLoading: false });
                  closeModal();
                  emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: update['user_ID']} });
             }else{
                setModalProps({ confirmLoading: false });
                notification.error({
                message: t('sys.update.error'),
                description: update_menu.msg,
                duration: 3,
              });
             }
          }else{
             setModalProps({ confirmLoading: true });
            // add
            var add_data = {
              password:values['Password'],
              confirmPassword:values['confirmPassword'],
              account:values['account'],
              phoneNum:values['phoneNum'],
              email:values['email'],
              dept:values['deptName'],
              role:values['roleId'],
            }
            const res = await AddAccount(add_data)
            if(res.code == 200){
                notification.success({
                message: t('sys.add.addsuccess'),
                description: t('sys.add.addsuccess'),
                duration: 3,
              });
               closeModal();
               emit('success');
             }else{
                notification.error({
                message: t('sys.add.addfail'),
                description: res.message,
                duration: 3,
              });
             }
              setModalProps({ confirmLoading: false });
          }
          // TODO custom api
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
